package com.example.androidstart.coroutines

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.androidstart.R
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlin.coroutines.cancellation.CancellationException

class CoroutineLearnActivity : AppCompatActivity() {
    private val TAG = "CoroutineLearnActivity"
    private var mCoroutineShowView: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_coroutine_layout)
        mCoroutineShowView = findViewById(R.id.coroutineCenterShowView)
        // activity 中没有的
        val job = lifecycleScope.launch((Dispatchers.IO)) {
            try {
                val data = fetchDataFromNetwork() // 后台执行
                withContext(Dispatchers.Main) { // 切换回主线程更新 UI
                    mCoroutineShowView?.setText(data)
                    Log.i(TAG, "onCreate: setText " + data)
                }

            } catch (e: CancellationException) {
                Log.i(TAG, "onCreate: cancel CancellationException")
            }
        }
        lifecycleScope.launch {
            try {
                doWorld()
            } catch (e: TimeoutCancellationException) {
                Log.i(TAG, "onCreate: TimeoutCancellationException")
            }
            Log.i(TAG, "onCreate: finish! ") // 4
        }
//        lifecycleScope.launch(Dispatchers.IO) {
//            repeat(50_000) { // launch a lot of coroutines
//                launch {
//                    delay(5000L)
//                    Log.i(TAG, "onCreate: repeat! ")
//                }
//            }
//        }
    }

    suspend fun doWorld() = coroutineScope { // this: CoroutineScope
        val job = launch {
            delay(2000L)
            Log.i(TAG, "World 2") // 3.
        }
        job.join()
        launch {
            try {
                withTimeout(1300L) {
                    repeat(1000) { i ->
                        println("I'm sleeping $i ...")
                        delay(500L)
                    }
                }
            } catch (e: TimeoutCancellationException) {
                Log.i(TAG, "onCreate: TimeoutCancellationException")
            }

            Log.i(TAG, "World 1") // 2.
        }
        Log.i(TAG, "Hello") // 1
    }

    // 示例：挂起函数（耗时操作）
    private suspend fun fetchDataFromNetwork(): String {
        delay(3000) // 模拟网络延迟（非阻塞）
        Log.i(TAG, "fetchDataFromNetwork: suspend end!")
        return "数据获取成功!"
    }


    override fun onResume() {
        super.onResume()

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "onDestroy: ")
    }
}

